package zcw.com.lib_leet_code;

/**
 * Created by 朱城委 on 2021/7/19.<br><br>
 *
 * 数字的补数
 */
public class Topic476 {

    public static void main(String[] args) {
        Topic476 instance = new Topic476();

        System.out.println(instance.findComplement(5));
        System.out.println(instance.findComplement(4));
        System.out.println(instance.findComplement(2));
        System.out.println(instance.findComplement(1));
    }

    public int findComplement(int num) {
        int result = 0;

        int temp = 1;
        while (num != 0) {
            if((num & 1) == 0) {
                result = result | temp;
            }

            temp = temp << 1;
            num = num >>> 1;
        }

        return result;
    }

    public int findComplement3(int num) {
        int result = 0;

        int counter = 0;
        while (num != 0) {
            if((num & 1) == 0) {
                result = result + (1 << counter);
            }

            counter++;
            num = num >>> 1;
        }

        return result;
    }

    public int findComplement2(int num) {
        int sum = 0;

        while (sum < num) {
            sum = (sum << 1) | 1;
        }

        return sum - num;
    }
}
